<?php

/**
 * sfWidgetFormScriptTag
 *
 * @author José Nahuel Cuesta Luengo <ncuesta@cespi.unlp.edu.ar>
 */
class sfWidgetFormScriptTag extends sfWidgetForm
{
  const
    CDATA_OPEN  = '//<![CDATA[',
    CDATA_CLOSE = '//]]>';

  protected function configure($options = array(), $attributes = array())
  {
    $this->addRequiredOption('script');

    $this->addOption('type', 'text/javascript');
    $this->addOption('use_cdata', true);
    $this->addOption('use_jquery', true);
    $this->addOption('wrap_in_function', true);

    $this->setHidden(true);
  }

  public function render($name, $value = null, $attributes = array(), $errors = array())
  {
    $html = <<<HTML
<script type="%type%">
%cdata_open%
%function_open%
%script%
%function_close%
%cdata_close%
</script>
HTML;

    $extras = $this->getExtras();

    return strtr($html, array(
      '%type%'           => $this->getOption('type'),
      '%cdata_open%'     => $extras['cdata_open'],
      '%cdata_close%'    => $extras['cdata_close'],
      '%script%'         => $this->getOption('script'),
      '%function_open%'  => $extras['function_open'],
      '%function_close%' => $extras['function_close']
    ));
  }

  protected function getExtras()
  {
    $extras = array(
      'cdata_open'     => '',
      'cdata_close'    => '',
      'function_open'  => '',
      'function_close' => ''
    );

    if ($this->getOption('use_cdata'))
    {
      $extras['cdata_open']  = self::CDATA_OPEN;
      $extras['cdata_close'] = self::CDATA_CLOSE;
    }

    if ($this->getOption('wrap_in_function'))
    {
      $extras['function_open']  = '(function('.($this->getOption('use_jquery') ? '$' : '').') {';
      $extras['function_close'] = '})('.($this->getOption('use_jquery') ? 'jQuery' : '').')';
    }

    return $extras;
  }

}